package cmd

import (
	"github.com/MzoroHaHa/dev-tools/backend/app/browser"
	cmdutils "github.com/MzoroHaHa/dev-tools/backend/app/cmd-utils"
	"github.com/MzoroHaHa/dev-tools/backend/app/logger"
	mainapp "github.com/MzoroHaHa/dev-tools/backend/app/main-app"
	"github.com/MzoroHaHa/dev-tools/backend/app/server"
	"github.com/spf13/cobra"
	"os"
)

var appLogger = logger.NewLogger("app")
var appCmd = &cobra.Command{
	Use:   "app",
	Short: "start app with all features.",
	Long:  `start app with all features, frontend server, localhost server`,
	Run: func(cmd *cobra.Command, args []string) {
		if !cmdutils.GetDontStartServer() {
			go func() {
				port := cmdutils.GetServerPort()
				// 启动服务
				ls := server.LocalServer{
					Port:        port,
					BindAddress: "localhost",
				}
				appLogger.Info("starting server", "server", ls.String())
				ls.InitGin()
				ls.Start()

			}()
		} else {
			appLogger.Error("server won't by running")
		}
		mainapp.Run()
		appLogger.Info("app exit")
		browser.CloseChrome()
		os.Exit(0)
	},
}

var port uint
var chrome string
var page string
var db string
var userDataDir string
var dontStartServer string

func init() {

	appCmd.Flags().UintVarP(&port, cmdutils.FlagPort, "p", 8080, "port to listen on")
	appCmd.Flags().StringVarP(&chrome, cmdutils.FlagChrome, "c", "", "chrome path to use")
	appCmd.Flags().StringVarP(&db, cmdutils.DBFile, "d", "", "database file path")
	appCmd.Flags().StringVarP(&page, cmdutils.PageAddr, "", "", "app page address, default: http://localhost:port/dt, port come from -p/--port or app.port in config file.")
	appCmd.Flags().StringVarP(&userDataDir, cmdutils.UserDataDir, "", "", "argument for chrome :"+cmdutils.UserDataDir+", default is in the {program-file-dir}/chrome")
	appCmd.Flags().StringVarP(&dontStartServer, cmdutils.DontStartServer, "", "", "if yes , local server would not be started.")

	rootCmd.AddCommand(appCmd)

}
